'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken');

class LoginController extends Controller {
  // 登录
  async login() {
    const { ctx, app } = this;
    const { username, password } = ctx.request.body;
    let user = await ctx.service.user.getUser({ username, password });
    if (user) {
      user = ctx.camelcaseKeys(user);
      const token = jwt.sign({ userId: user.userId }, app.config.jwtSecret, { expiresIn: '7d' });
      // await app.redis.setex(user.userId, 15, token);
      await app.redis.setex(user.userId, 24 * 60 * 60, token);
      ctx.returnBody({
        data: {
          user,
        },
        message: '登录成功',
      });
    } else {
      ctx.returnBody({
        code: 400,
        message: '用户名或密码错误',
      });
    }
  }

  // 登出
  async logout() {
    const { ctx, app } = this;
    const userId = ctx.request.headers['user-id'];
    if (userId) {
      await app.redis.del(userId);
    }
    ctx.returnBody({
      message: '退出登录成功',
    });
  }
}

module.exports = LoginController;
